﻿CREATE TRIGGER [TRG_Project_Delete]
	ON [dbo].[Project]
	INSTEAD OF DELETE
AS
BEGIN
	SET NOCOUNT ON

	BEGIN TRY

		BEGIN TRAN

		DELETE D
		FROM [dbo].[Data] D
		INNER JOIN [dbo].[DataCategory] DSC ON DSC.[DataCategoryId] = D.[DataCategoryId]
		WHERE DSC.[Level] = 1 AND [ProjectId] in (SELECT [ProjectId] FROM deleted)

		DELETE FROM [dbo].[Rule]
		WHERE [ProjectId] in (SELECT [ProjectId] FROM deleted)

		DELETE FROM [dbo].[Template]
		WHERE [ProjectId] in (SELECT [ProjectId] FROM deleted)

		DELETE FROM [dbo].[TransformationSetting]
		WHERE [ProjectId] in (SELECT [ProjectId] FROM deleted)

		DELETE FROM [dbo].[Project]
		WHERE [ProjectId] in (SELECT [ProjectId] FROM deleted)

		IF @@TRANCOUNT > 0
			COMMIT TRAN;
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
			ROLLBACK TRAN;
		THROW;
	END CATCH
END

